package com.hb.trans.mvp.ui.activity


import android.os.Bundle
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.basiclib.base.BaseActivity
import com.hb.trans.R
import com.hb.trans.global.ACTIVITY_FLUTTER
import com.hb.trans.mvp.presenter.NewDetailPresenter
import dagger.android.AndroidInjection
import io.flutter.facade.Flutter
import io.flutter.plugin.common.MethodChannel
import io.flutter.view.FlutterView
import kotlinx.android.synthetic.main.activity_flutter.*
import javax.inject.Inject


@Route(path = ACTIVITY_FLUTTER)
class MyFlutterActivity : BaseActivity() {
    private var flutterView: FlutterView? = null
    private val CHANNELDATA = "getData4Flutter"
    private val CHANNELMETHOD = "getMethod4Flutter"
    lateinit var data: String
    @Inject
    override fun getContentViewResId(): Int = R.layout.activity_flutter

    override fun onActivityInject() {
        AndroidInjection.inject(this)
    }

    override fun attachView(savedInstanceState: Bundle?) {
        ARouter.getInstance().inject(this)
    }

    override fun getPresenter(): NewDetailPresenter? = null

    override fun initView() {

        flutterView = Flutter.createView(this, lifecycle, "route1")
//        val layout = FrameLayout.LayoutParams(matchParent, matchParent)
//        addContentView(flutterView, layout)

        flutter_container.addView(flutterView)
        val listeners = arrayOfNulls<FlutterView.FirstFrameListener>(1)
        listeners[0] = FlutterView.FirstFrameListener { flutter_container.visibility = View.VISIBLE }
        flutterView!!.addFirstFrameListener(listeners[0])
    }

    override fun initData() {
        data = intent.getStringExtra("pageIndex")
        MethodChannel(flutterView, CHANNELDATA).setMethodCallHandler { methodCall, result ->
            run {
                when {
                    methodCall.method == "getData" -> result.success(data)
                    else -> result.notImplemented()
                }
            }
        }

        MethodChannel(flutterView, CHANNELMETHOD).setMethodCallHandler { methodCall, result ->
            run {
                when {
                    methodCall.method == "onBackPressed" -> onBackPressed()
                    else -> result.notImplemented()
                }
            }
        }


    }


    override fun setListener() {}


    override fun onBackPressed() {
        if (flutterView != null) {
            flutterView!!.popRoute()
        } else {
            super.onBackPressed()
        }
    }
}
